package sa.com.sure.ejtimaa;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


import sa.com.sure.ejtimaa.R.style;
import sa.com.sure.ejtimaa.common.AppDialogs;
import sa.com.sure.ejtimaa.common.Helper;
import sa.com.sure.ejtimaa.database.MeetingAttendees;
import sa.com.sure.ejtimaa.database.MeetingPlaces;
import sa.com.sure.ejtimaa.database.MeetingSessions;
import sa.com.sure.ejtimaa.database.MeetingStatuses;
import sa.com.sure.ejtimaa.database.Meetings;
import sa.com.sure.ejtimaa.model.MeetingInfo;
import sa.com.sure.ejtimaa.model.MeetingPlaceInfo;
import sa.com.sure.ejtimaa.model.MeetingSessionInfo;
import android.app.Activity;

import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.SQLException;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;


public class MeetingListFragment extends ListFragment  {
		
		private List<MeetingInfo> meetings = null;
		
		private meetingAdapter	mAdapter = null;
		
		private Runnable viewMeetings;

		//MeetingDetailFragment meetingDetailFragment = null;
		
		private ProgressDialog m_ProgressDialog = null;
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

		}
		
		
	    @Override
	    public void onActivityCreated(Bundle savedInstanceState) {  
		    try
		    {
		        super.onActivityCreated(savedInstanceState);
		       		
		        meetings = new ArrayList<MeetingInfo>();
		                
		        this.mAdapter = new meetingAdapter(getActivity(), R.layout.meetings_list_item, meetings);
		        
		        setListAdapter(this.mAdapter);
		        
		        getData();
		        
		        ListView listView = getListView();
		        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		        
			}
			catch(Exception ex){    		
		    	Helper.HandleError(ex,true);
			}              
	    }
	        
	    @Override
		public void onStart(){
	    	
	    	try
		    {
	    		super.onStart();	    		
	    		//meetingDetailFragment  =(MeetingDetailFragment) getActivity().getFragmentManager().findFragmentById(R.id.detailFragment);
			}
			catch(Exception ex){    		
		    	Helper.HandleError(ex,true);
			}  
	    }
	    
	    
	    
	    @Override
		public void onListItemClick(ListView l, View v, int position, long id) {
	    	try
	    	{
		    	mAdapter.setSelectedPosition(position);
		    	Helper.StartActivity(MeetingDetialActivity.class,(Serializable) meetings.get(position));
		    	//meetingDetailFragment.SetData(meetings.get(position));
			}
			catch(Exception ex){    		
		    	Helper.HandleError(ex,true);
			}  
	    }
	    
	    public void RefershDataList(){
	    	
	    	mAdapter.items.clear();
    		getData();
	    }
	    

	    
		private class meetingAdapter extends ArrayAdapter<MeetingInfo> {

			private List<MeetingInfo> items = null;
			
			private int selectedPos = -1;
			
			public meetingAdapter(Context context, int textViewResourceId ,List<MeetingInfo> items ) {
				super(context, textViewResourceId, items);
	            this.items = items;
			}
		
			public void setSelectedPosition(int pos){
				selectedPos = pos;
				notifyDataSetChanged();
			}


			
		    @Override
	        public View getView(int position, View convertView, ViewGroup parent) {
		    	
		    	View v = convertView;
		    	
		    	try{
		                
		                if (v == null) {
		                    LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		                    v = vi.inflate(R.layout.meetings_list_item, null);
		                }
		                MeetingInfo m = items.get(position);
		                if (m != null) {
		                	
		                        TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
		                        TextView tvMeetingNo = (TextView) v.findViewById(R.id.tvMeetingNo);
		                        TextView tvMeetingStatus = (TextView) v.findViewById(R.id.tvMeetingStatus);
		                        TextView tvStartDate = (TextView) v.findViewById(R.id.tvStartDate);
		                        TextView tvEndDate = (TextView) v.findViewById(R.id.tvEndDate);	                        
		                        TextView tvAttendance = (TextView) v.findViewById(R.id.tvAttendance);	
		                        TextView tvAbsence = (TextView) v.findViewById(R.id.tvAbsence);	
		                        TextView tvSession = (TextView) v.findViewById(R.id.tvSession);	
		                        TextView tvMeetingPlace = (TextView) v.findViewById(R.id.tvMeetingPlace);	
		                        TextView tvWaitingForAttendeesReply = (TextView) v.findViewById(R.id.tvWaitingForAttendeesReply);	
		                        
		                        if (tvTitle != null) {
		                        		                        
		                        	
		                        	tvTitle.setText(m.GetTitle());
		                        	tvMeetingNo.setText(m.GetMeetingNo());
		                        	tvMeetingStatus.setText(MeetingStatuses.Instance.GetItem(m.GetMeetingStatusID()).GetMeetingStatusName());	 
		                        	tvAbsence.setText(Integer.toString((MeetingAttendees.Instance.GetItemsCountByMeetingIDAndAttended(m.GetMeetingID(),false))));		                        	
		                        	tvAttendance.setText(Integer.toString(MeetingAttendees.Instance.GetItemsCountByMeetingIDAndAttended(m.GetMeetingID(),true)));
		                        	tvWaitingForAttendeesReply.setText(Integer.toString(m.GetWaitingForAttendeesReply()));
		                        	
		                        	MeetingSessionInfo meetingSession =  MeetingSessions.Instance.GetItem(m.GetMeetingID());
		                        	if(meetingSession != null)
		                        		tvSession.setText(meetingSession.GetSessionName());
		                        	else
		                        		tvSession.setText(getString(R.string.Nothing));
		                        	
		                        	MeetingPlaceInfo meetingPlace =  MeetingPlaces.Instance.GetItem(m.GetMeetingID());
		                        	if(meetingSession != null)
		                        		tvMeetingPlace.setText(meetingPlace.GetMeetingPlaceName());
		                        	else
		                        		tvMeetingPlace.setText(getString(R.string.Nothing));
		                        
		                        	try
		                        	{		                        	
									    tvStartDate.setText(Helper.GetDateAsStringFormat(m.GetStartDate(), Helper.DateFormatLabel));						
			                        	tvEndDate.setText(Helper.GetDateAsStringFormat(m.GetEndDate(), Helper.DateFormatLabel));
		                    		} catch (ParseException ex) {
										Helper.HandleError(ex);
									}		                        	
		                        }
		                        	                       
		                        
		                        if(selectedPos == position){
		                        	v.setBackgroundColor(Color.GRAY);
		            	        	
		            	        }else{
		            	        	v.setBackgroundColor(Color.TRANSPARENT);
		            	        }
		                        			                     		        
		                  }
		                
		                
		                
				}
				catch(Exception ex){    		
			    	Helper.HandleError(ex,true);
				} 
		    	
		    	return v;
		   }
 	    
	    }
		
		private void getData(){
			
			
	        viewMeetings = new Runnable(){
	            public void run() {
	            	try {
						meetings = Meetings.Instance.GetAllItems();
						Thread.sleep(1000);
						
						handler.sendMessage(handler.obtainMessage(Activity.RESULT_OK));
					} catch (SQLException e) {
						handler.sendMessage(handler.obtainMessage());
						Helper.HandleError(e);
					} catch (ParseException e) {
						handler.sendMessage(handler.obtainMessage());
						Helper.HandleError(e);
					} catch (InterruptedException e) {
						handler.sendMessage(handler.obtainMessage());
						Helper.HandleError(e);
					}
	            }
	        };
	                
	        Thread thread =  new Thread(null, viewMeetings, "MagentoBackground");
	        thread.start();
	        m_ProgressDialog = AppDialogs.ProgressWaitingDialog(this.getActivity());			
		}
		
	    Handler handler = new Handler() {
	        public void handleMessage(Message msg) { 
	        	if(msg.what==Activity.RESULT_OK)
	        	{
	            	if(meetings != null && meetings.size() > 0){
	            		mAdapter.clear();	
	                    mAdapter.addAll(meetings);
	                 }
	             	
	        		mAdapter.notifyDataSetChanged();						
	        	}
	        	else        		
	        		Helper.ShowToast(R.string.GlobalError);
	        	     
	        	m_ProgressDialog.dismiss();	
	        }
	    };
	    

}
